//==================================================================
/// font.cpp
///
/// Created by Davide Pasca - 2009/10/5
/// See the file "license.txt" that comes with this project for
/// copyright info. 
//==================================================================

#include "stdafx.h"
#include "font.h"

//==================================================================
Font::Font( const DStr &fname, int fw, int fh ) :
	mImg( fname, 8 )
{
	for (size_t i=0; i < 256; ++i)
	{
		mSrcCoords[0][i] = 0;
		mSrcCoords[1][i] = 0;
	}

	mCWd = fw;
	mCHe = fh;

	int w = mImg.mW;
	int h = mImg.mH;

	DVec<U8>	pixels_out;
	pixels_out.resize( w * h );
	for (size_t i=0; i < pixels_out.size(); ++i)
		pixels_out[i] = 0;

	int	x, y, xx, yy;
	U8	col;

	int i = 1+mImg.mW;
	for (y=1; y < h-1; ++y, ++i)
	{
		for (x=1; x < w-1; ++x, ++i)
		{
			col = mImg.GetPU8()[i];
			if ( col != 0 )
				for (yy=-w; yy <= w; yy += w)
					for (xx=-1; xx <= 1; ++xx)
						pixels_out[i+xx+yy] = col;
		}
	}

	mImgOutline = image( pixels_out, w, h );

	int	sx, sy;

	sx = 0;
	sy = 0;
	for (i=32; i < 32+32*3; ++i)
	{
		if ( (U32)(sx + fw+1) > mImg.mW )
		{
			sx = 0;
			sy += fh+1;
			if ( (U32)(sy + fh) > mImg.mH )
				break;
		}

		mSrcCoords[0][i] = sx;
		mSrcCoords[1][i] = sy;

		sx += fw+1;
	}
}

//==================================================================
void Font::DrawText( graphics &g, int x, int y, int align_x, int align_y, int col1, int col2, int bgcol, const DStr &str )
{
	int		ch;
	int		sx, sy;
	int		str_wd;

	bgcol |= 0xff000000;

	int len = str.length();

	str_wd = len * (mCWd-4);

	if ( align_x == 0 )	x -= str_wd/2;	else
		if ( align_x > 0 )	x -= str_wd;

	if ( align_y == 0 )	y -= mCHe/2;	else
		if ( align_y > 0 )	y -= mCHe;

	for (int i=0; i < len; ++i)
	{
		ch = str[ i ];
		if ( ch >  32 && ch <= 32+32*3 )
		{
			sx = mSrcCoords[0][ch];
			sy = mSrcCoords[1][ch];

			g.image_draw( mImgOutline, sx, sy, mCWd, mCHe, x, y, bgcol );
			g.image_draw( mImg, sx, sy, mCWd, mCHe, x, y, col1, col2 );
		}
		x += mCWd-4;
	}
}
